<template>
  <div>
    <mk-breadcrumb  :breadcrumb-data="breadcrumbData"></mk-breadcrumb>
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-fixedHeightSmall)+'px'}]">
      <div class="content-box">
        <div class="add-page-box">
          <div class="add-page-content-box">
            <el-form :model="pageContentData" ref="pageForm" label-position="right" label-width="96px"
                     class="top-form" :rules="submitFormRules">
              <el-form-item label="页面名称" prop="title">
                <el-input v-model="pageContentData.title" placeholder="请输入页面名称（必填，80字内）" :maxlength="80"></el-input>
              </el-form-item>
              <el-form-item label="关键词" prop="keyWord">
                <el-input v-model="pageContentData.keyWord" placeholder="请输入关键词（选填，英文逗号分开）"></el-input>
              </el-form-item>
              <el-form-item label="页面描述" prop="description">
                <el-input v-model="pageContentData.description" placeholder="请输入页面描述（选填，200字内）" type="textarea" :rows="6" resize="none"></el-input>
              </el-form-item>
              <el-form-item label="页面图标" prop="iconId">
                <el-upload
                  class="avatar-uploader"
                  accept=".jpg, .png"
                  :show-file-list="false"
                  :data="{'width':200,'height':200}"
                  :on-success="handleSuccess"
                  :before-upload="beforeCoverUpload"
                  name="image"
                  :action="'/upload/image.json'">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <span style="color:#83a0a5;font-size:14px;">建议上传尺寸200*200</span>
              </el-form-item>
              <el-form-item label="页面正文" prop="content" class="ckeditor-content-size">
                <mk-ckeditor v-model="pageContentData.content" class="article-editor"></mk-ckeditor>
                <p style="color:#83a0a5;font-size:14px;text-align: left;">建议文章内容中的图片宽度不超过800</p>
              </el-form-item>
            </el-form>
          </div>

          <div class="ensure-save-box">
            <el-button class="btnStyle color2" type="primary" v-if="!pageContentData.publish" v-loading.fullscreen.lock="fullscreenLoading" @click="handlePage('pageForm','ENABLE')"  >发布
            </el-button>

            <el-button class="btnStyle color2" type="primary" v-if="!pageContentData.publish" v-loading.fullscreen.lock="fullscreenLoading" @click="handlePage('pageForm','DISABLE')" >保存
            </el-button>
            <el-button class="btnStyle color2" type="primary"  v-loading.fullscreen.lock="fullscreenLoading" @click="previewPage('pageForm')" >预览
            </el-button>
            <div class='btnStyle color2' v-if="!isAdd" v-clipboard = 'copyLink' @success="copySuccess" @error="copyError">复制链接</div>
          </div>

        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script>
//  import {PROPERTY_HOST} from '../../../utils/constants'
  import MkBreadcrumb from '../../../components/MkBreadcrumb.vue'
  import singlePageService from '../../../services/singlePage'
  import {mapState} from 'vuex'
  export default {
  	name: 'addSinglePage',
    components: {
      MkBreadcrumb,
    },
    methods: {
      copyLink() {
//        return PROPERTY_HOST+'/mi/article/detailView.htm?siteId='+this.siteId+'&pageId='+this.articleDetailData.id+'&app=true';
        return this.copyUrl;
      },

      beforeCoverUpload(file) {
        let fileName = file.name;
        let suffix = fileName.substr(file.name.lastIndexOf("."), fileName.length).toLowerCase();
        let support = false;
        for (let i = 0; i < this.supportFile.length; i++) {
          if (suffix === this.supportFile[i]) {
            support = true;
            break;
          }
        }
        if (!support) {
          this.$message.warning('只能上传图片格式的文件');
          return support;
        }
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          this.$message.error('图片大小不能超过 1MB!');
        }
        return isLt1M;
      },
      copySuccess(e) {
        this.$message.success('复制成功');
      },
      copyError(e) {
        this.$message.warning('复制失败');
      },
      handleSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.pageContentData.iconId = res.data.fileId;
      },
      previewPage(formName){

      	this.$refs[formName].validate((valid) => {

      		if (valid){
            let param = {};
            let pageContentData = this.pageContentData;
            this.isSubmit = false;
            if(!this.isSubmit) {
              let win = window.open();
              if(!pageContentData.id){
                param = {
                  content: pageContentData.content,
                  icon: pageContentData.iconId,
                  description: pageContentData.description,
                  name: pageContentData.title,
                  keyWord:pageContentData.keyWord,
                  status:'DISABLE'
                }
                this.isSubmit = false;
                singlePageService.editPageServer(param, (data)=> {
                  let previewId = data.data;
                  this.pageContentData.id = previewId;
                  singlePageService.operatePage({id:previewId,type:'PREVIEW'},data=>{
                    win.location = data.data.url
                  })
                  return this.pageContentData.id
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              } else {
                param = {
                  id:pageContentData.id,
                  content: pageContentData.content,
                  icon: pageContentData.iconId,
                  description: pageContentData.description,
                  name: pageContentData.title,
                  keyWord:pageContentData.keyWord,
                  status:'DISABLE'
                }
                this.isSubmit = false;
                if (pageContentData.publish===true){
                  singlePageService.operatePage({id:pageContentData.id,type:'PREVIEW'},data=>{
                    win.location = data.data.url
                  })
                }else {
                  singlePageService.editPageServer(param,  (data)=> {
                    let previewId = data.data;
                    singlePageService.operatePage({id:previewId,type:'PREVIEW'},data=>{
                      win.location = data.data.url
                    })
                  },(data)=>{
                    this.isSubmit = false;
                    this.fullscreenLoading = false;
                  })
                }

              }
            }
          }
        });
      },


      handlePage(formName,btnStatus) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {};
            let pageContentData = this.pageContentData;
            this.isSubmit = false
            if (!this.isSubmit) {
              if (!pageContentData.id) {
                console.log("noID");
                param = {
                  content: pageContentData.content,
                  icon: pageContentData.iconId,
                  description: pageContentData.description,
                  name: pageContentData.title,
                  keyWord:pageContentData.keyWord,
                  status:btnStatus
                }
                this.isSubmit = true;
                this.fullscreenLoading = true;
                singlePageService.editPageServer(param,  (data) =>{
                  this.$message({
                    message:'操作成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/singlePage'});
                    this.isSubmit = false;
                  },1000);
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              } else {
              	console.log("hasID");
                param = {
                  id:pageContentData.id,
                  content: pageContentData.content,
                  icon: pageContentData.iconId,
                  description: pageContentData.description,
                  name: pageContentData.title,
                  keyWord:pageContentData.keyWord,
                  status:btnStatus
                }
                this.isSubmit = true;
                this.fullscreenLoading = true;
                singlePageService.editPageServer(param,  (data)=> {
                	console.log(data);
                  this.$message({
                    message:'操作成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/singlePage'});
                  },1000);

                  this.isSubmit = false;
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              }
            }

          }
        })
      },


    },
    computed: mapState({
      bodyHeight: state => state.global.bodyHeight,
      fixedHeightSmall: state => state.global.fixedHeightSmall,

    }),
    mounted: function () {
      let pageId = this.$route.params.id;
      this.pageContentData.id = this.$route.params.id;
      this.status = this.$route.params.status;
      this.copyUrl = this.$route.params.url;
      if(pageId) {
//        this.onlyPub = true;
        this.breadcrumbData.list[2].name = '查看页面';
        this.pageContentData.id = pageId;
        singlePageService.loadPageDetail({id:pageId},data => {
          let detail = data.data;
          let pageContentData =  this.pageContentData;
          pageContentData.title = detail.title;
          pageContentData.content = detail.content;
          pageContentData.description = detail.description;
          pageContentData.keyWord = detail.keyWord;
          pageContentData.iconId = detail.iconId;
          pageContentData.publish = detail.publish;
          this.imageUrl = detail.iconUrl;
        })
      }else{
        this.breadcrumbData.list[2].name = '新增页面';
        this.isAdd = true;
      }
    },
    activated(){
    },
    data() {
      let validateContent = (rule, val, callback) => {
        let value = (val + '').trim();
        if (value === '') {
          callback('请输入正文');
        } else {
          callback();
        }
      };
      return {
        status: '',
        copyUrl:'',
        isAdd:false,
        fullscreenLoading: false,
        supportFile: ['.jpg', '.png'],
        isSubmit: false,
        onlyPub: false,
        breadcrumbData: {
          list: [
            {
              name: '运营',
              path: null,
              clickAble: false
            },{
              name: '单页面',
              path: '/operationMgt/singlePage',
              clickAble: true
            },{
              name: '编辑页面',
              path: null,
              clickAble: false
            }
          ],
          returnData: {
            isReturn: true, path: null
          },
          iconName: 'operation-icon',
        },
        pageContentData: {
          id: "",
          title: "",
          content: "",
          description: "",
          keyWord:'',
          iconUrl: "",
          iconId:'',
          url:'',
          publish:''
        },
        imageUrl: '',
        submitFormRules: {
          title: [
            {required: true, message: "请输入页面名称", trigger: 'change'},
            {max: 80, message: '不超过80个字符', trigger: 'change'},
//            {min: 1, message: '不少于1个字符', trigger: 'change'}
          ],
          description:{max: 200, message: '不超过200个字符', trigger: 'change'},
          content: {validator: validateContent, trigger: 'change'},
        },

      }
    }

  }
</script>

<style lang="less">
  @import '../../../assets/style/main.less';
  .add-page-box {
    .addNode{
      display:inline;
      cursor:pointer;
      color: @creatButton;
      i{
        color:@creatButton;
      }
      &:hover{
        .my-opacity();
      }
    }
    .add-page-content-box {
      margin-top: 0px;
      padding: 30px;
      background-color: #fff;
    }
    .top-form .el-form-item {
      width: 600px;
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: @primaryColor;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .ensure-save-box {
      background-color: @primaryColor;
      padding: 30px 40px;
      .color1 {
        color: @primaryColor;
      }
      .color2 {
        color: @creatButton;
      }
      .btnStyle {
        min-width: 120px;
        display: inline-block;
        height: 40px;
        background-color: #fff;
        text-align: center;
        line-height: 40px;
        border-radius: 5px;
        margin-right: 60px;
        cursor: pointer;
        font-size: 14px;
      }
    }
  }

  .ql-container .ql-editor {
    min-height: 320px;
    padding-bottom: 16px;
    max-height: 400px;
  }

  .ckeditor-content-size {
    width: 800px !important;
  }


</style>
